package derek.sun;

import java.awt.BorderLayout;
import java.awt.List;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.RandomAccessFile;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import static derek.sun.Utils.*;

public class Frame extends JFrame {
	private static final long serialVersionUID = 1L;
	JButton btnRefresh = new JButton("Refresh");
	JButton btnAdd = new JButton("Add Keyword");
	JButton btnDelete = new JButton("Delete Keyword");

	JTextField txtServer = new JTextField(10);
	JTextField txtUser = new JTextField(10);
	JTextField txtContext = new JTextField(30);

	JLabel lblServer = new JLabel("lblServer");
	JLabel lblUser = new JLabel("lblUser");
	JLabel lblContext = new JLabel("Key:");

	MyTree tree;

	Clipboard cb;

	JComboBox cmbUsers = new JComboBox();

	List lstMsg = new List(10, true);

	JPanel p1 = new JPanel();
	JPanel p2 = new JPanel();
	JPanel p3 = new JPanel();
	JPanel p4 = new JPanel();

	public void addTreeRootLayer(String reg) {
		DefaultMutableTreeNode top = new DefaultMutableTreeNode(reg);
		tree = new MyTree(top);
	}

	public void addTreeAction() {
		tree.addTreeSelectionListener(new TreeSelectionListener() {
			public void valueChanged(TreeSelectionEvent e) {
				if (e.getPath().getPathCount() == 4) {
					String stringURL = ((DefaultMutableTreeNode) tree
							.getLastSelectedPathComponent()).getUserObject()
							.toString();
					System.out.println(stringURL);
					try {
						StringSelection stsel = new StringSelection(stringURL);
						Toolkit.getDefaultToolkit().getSystemClipboard()
								.setContents(stsel, null);
					} catch (Exception e1) {
						e1.printStackTrace();
					}

				}
			}
		});
	}

	public Frame() {
		super("美剧追踪工具");
		this.setDefaultCloseOperation(EXIT_ON_CLOSE);
		this.setLayout(new BorderLayout());

		try {
			BufferedReader br = new BufferedReader(new FileReader(
					"d:/config.sy"));
			String str = "";
			String r = br.readLine();
			while (r != null) {
				str += r;
				r = br.readLine();
			}
			String[] split = str.split(",");
			for (int i = 0; i < split.length; i++) {
				cmbUsers.addItem(split[i].trim());
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		addTreeRootLayer("roor");
		addTreeAction();

		p1.setLayout(new BorderLayout());
		p1.setAutoscrolls(true);

		p1.add(lstMsg);
		p1.add(new JScrollPane(tree));
		p1.add(p3, BorderLayout.SOUTH);

//		p2.add(lblUser);
//		p2.add(txtUser);
//		p2.add(lblServer);
//		p2.add(txtServer);

		p3.add(cmbUsers);
		p3.add(lblContext);
		p3.add(txtContext);
		p3.add(btnAdd);
		p3.add(btnDelete);
		p3.add(btnRefresh);
		
		btnRefresh.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent arg0) {
				tree.updateUI();
			}
		});

		btnAdd.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				String expectAdd = txtContext.getText();
				if (expectAdd.trim().length() < 2) {
					JOptionPane.showMessageDialog(Frame.this, "输入字符太短", "提示 ",
							JOptionPane.ERROR_MESSAGE);
					return;
				}
				try {
					String fileName = "d:/config.sy";
					for (int i = 0; i < cmbUsers.getItemCount(); i++) {
						if (Utils.strComIgnoreCase(cmbUsers.getItemAt(i)
								.toString().trim(), expectAdd.trim())) {
							JOptionPane.showMessageDialog(Frame.this, "已经存在 ",
									"提示 ", JOptionPane.ERROR_MESSAGE);
							return;
						}
					}
					RandomAccessFile randomFile = new RandomAccessFile(
							fileName, "rw");
					long fileLength = randomFile.length();
					randomFile.seek(fileLength);
					randomFile.writeBytes("," + expectAdd);
					randomFile.close();
					cmbUsers.addItem(expectAdd.trim());
					JOptionPane.showMessageDialog(Frame.this, "添加成功", "提示 ",
							JOptionPane.OK_OPTION);

				} catch (FileNotFoundException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		});

		btnDelete.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent arg0) {
				String expectAdd = txtContext.getText();
				if (expectAdd.trim().length() < 2) {
					JOptionPane.showMessageDialog(Frame.this, "输入字符太短", "提示 ",
							JOptionPane.ERROR_MESSAGE);
					return;
				}
				try {
					String fileName = "d:/config.sy";
					for (int i = 0; i < cmbUsers.getItemCount(); i++) {
						if (Utils.strComIgnoreCase(cmbUsers.getItemAt(i)
								.toString().trim(), expectAdd.trim())) {
							BufferedReader br = new BufferedReader(
									new FileReader(fileName));
							String text;
							String buffer = "";
							while ((text = br.readLine()) != null) {
								buffer += (text + "\n");
							}
							buffer.replaceFirst(expectAdd.trim(), "");
							buffer.replaceFirst(",,", ",");
							// textArea.append(text + "\n");
							RandomAccessFile randomFile = new RandomAccessFile(
									fileName, "rw");
							randomFile.writeBytes(buffer);
							randomFile.close();
							cmbUsers.removeItemAt(i);
							JOptionPane.showMessageDialog(Frame.this, "删除成功",
									"提示 ", JOptionPane.OK_OPTION);
							return;
						}
					}
					JOptionPane.showMessageDialog(Frame.this, "无效删除",
							"提示 ", JOptionPane.OK_OPTION);

				} catch (FileNotFoundException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		});

//		this.add(p2, BorderLayout.SOUTH);
		this.add(p1, BorderLayout.CENTER);
		this.pack();
		this.setVisible(true);

		String reg;
		for (int i = 0; i < cmbUsers.getItemCount(); i++) {
			reg = cmbUsers.getItemAt(i).toString();
			DefaultMutableTreeNode second = new DefaultMutableTreeNode(reg);
			tree.addSubNode(tree.firstClassNode, second);
		}
	}
}
